﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Net;
using System.Windows.Forms;
using System.Collections;

namespace SELF.Model
{
    class Leaning
    {
        private static lcmpt.Connection conn = new lcmpt.Connection();

        public static DataSet ExecuteStoreDataSet(string storeName, string ConnectionString)
        {
            try
            {
                SqlConnection connection = new SqlConnection(ConnectionString);
                if (connection.State != ConnectionState.Open)
                {
                    connection.Open();
                }
                //SqlCommand command = new SqlCommand();
                //command.CommandType = CommandType.StoredProcedure;
                //command.Connection = connection;
                //command.CommandTimeout = ConnectionTimeOut;
                SqlDataAdapter adapter = new SqlDataAdapter(storeName,connection);
                adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
                adapter.SelectCommand.CommandTimeout = 36000;
                DataSet dataSet = new DataSet();
                adapter.Fill(dataSet, "DATA");
                connection.Close();
                connection.Dispose();
                return dataSet;
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }
        }
        public static string Int2TimeWithSec(int intDate)
        {

            int hr = intDate / 3600;
            int min = (intDate % 3600) / 60;
            int sec = (intDate % 3600) % 60;
            string strHr = hr.ToString();
            string strMin = min.ToString();
            string strSec = sec.ToString();

            if (strHr.Length == 1)
            {
                strHr = "0" + strHr;
            }
            if (strMin.Length == 1)
            {
                strMin = "0" + strMin;
            }

            if (strSec.Length == 1)
            {
                strSec = "0" + strSec;
            }

            string datime = strHr + ":" + strMin + ":" + strSec;

            return datime;
        }
        public static string GetIP()
        {
            IPHostEntry host;
            string localIP = "?";
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily.ToString() == "InterNetwork")
                {
                    localIP = ip.ToString();
                }
            }
            return localIP;

        }

        public static bool SetMechineState(StateMechine state)
        {
            try
            {
                string studentName = "";
                string TicketID = "";

                switch (state)
                {
                    case StateMechine.Open: studentName = ""; TicketID = ""; VDOStatus.PlayingState = false;
                        break;
                    case StateMechine.Logon: studentName = Common.Member.MemberName; TicketID = Common.Member.TicketID; VDOStatus.PlayingState = false;
                        break;
                    case StateMechine.Play: studentName = Common.Member.MemberName; TicketID = Common.Member.TicketID; VDOStatus.PlayingState = true;
                        break;
                    case StateMechine.Close: studentName = ""; TicketID = ""; VDOStatus.PlayingState = false;
                        break;
                    case StateMechine.Error: studentName = ""; TicketID = ""; VDOStatus.PlayingState = false;
                        break;
                }


                string mState = state.ToString();
                string query = @"EXECUTE  [dbo].[sp_Upd_Stations] '@State', '@Ticket', '@Name', '@IP'";
                query = query.Replace("@State", mState);
                query = query.Replace("@Ticket", TicketID);
                query = query.Replace("@Name", studentName);
                query = query.Replace("@IP", GetIP());
                conn.Execute(query);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        public enum StateMechine
        {
            Open,
            Play,
            Close,
            Logon,
            Error
        }

        public static bool IsFormAlreadyOpen(Type FormType)
        {
            foreach (Form OpenForm in Application.OpenForms)
            {
                if (OpenForm.GetType() == FormType)
                    return true;
            }

            return false;
        }

        /// <summary>
        /// Input as time in format 08.00-08.30,calculate as two number.
        /// Example input 08.00-08.30 this will return value[0]=480,value[1]=510 
        /// </summary>
        public static ArrayList TimeToValue(string time)
        {
            ArrayList retValue = new ArrayList();
            string[] input = time.Split('-'); //time=08.00-08.30,input[0]=08.00,input[1]=08.30
            foreach (string cTime in input)
            {
                string[] hTime = cTime.Split('.');//cTime=08.00,hTime[0]=08,hTime[1]=00
                int numValue=0;
                numValue = Convert.ToInt32(hTime[0]) * 60;
                numValue += Convert.ToInt32(hTime[1]);
                retValue.Add(numValue);
            }

            return retValue;
        }

        public static int TimeToValue(DateTime cTime)
        {
            int numValue = 0;
            numValue = cTime.Hour * 60;
            numValue += cTime.Minute;
            return numValue;
        }
        public static int TimeToValueWithSec(DateTime cTime)
        {
            int numValue = 0;
            numValue = cTime.Hour * 60 * 60 ;
            numValue += cTime.Minute * 60;
            numValue += cTime.Second;
            return numValue;
        }

        public static DateTime GetServerTime()
        {
            string sql = "SELECT GETDATE()";
            using (DataSet datetime = conn.Retreive(sql))
            {
                DateTime dt = Convert.ToDateTime(datetime.Tables[0].Rows[0][0].ToString());
                return dt;
            }
        }

        /// <summary>
        /// [1]calculate time between 2 datetime return time in format 10:01:10 
        /// </summary>
        public static string TimeRemainning(DateTime currentTime, DateTime destinationTime)
        {
            TimeSpan span = destinationTime.Subtract(currentTime);
            string datetime = "" + span.Hours + ":" + span.Minutes + ":" + span.Seconds;
            return datetime;
        }
        /// <summary>
        /// [1]get datetime fron integer like 630 to 10.30.00 of this day. calculte from mechine time.
        /// </summary>
        public static DateTime Int2Datetime(int intDate)
        {
            int hr = intDate / 60;
            int min = intDate % 60;
            DateTime dtNow = SELF.Model.Leaning.GetServerTime();
            string datime = dtNow.ToShortDateString() + " " + hr + ":" + min + ":" + "00";

            DateTime dt = Convert.ToDateTime(datime);
            return dt;
        }

        public static string Int2Time(int intDate)
        {

            int hr = intDate / 60;
            int min = intDate % 60;
            string strHr = hr.ToString();
            string strMin = min.ToString();

            if (strHr.Length == 1)
            {
                strHr = "0" + strHr;
            }
            if (strMin.Length == 1)
            {
                strMin = "0" + strMin;
            }

            string datime = strHr + ":" + strMin + ":" + "00";

            return datime;
        }

        public static int strTime2Int(string strDate)
        {
            string[] a = strDate.Split(':');

            int time = ((Convert.ToInt32(a[0])*60) + Convert.ToInt32(a[1]));

            return time;
        }

        private static bool ServerSelector(string connectionString)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                try
                {
                    connection.Open();
                    return true;
                }
                catch (SqlException)
                {
                    return false;
                }
                finally
                {
                    // not really necessary
                    connection.Close();
                }
            }
        }


    }
}
